package com.stylefeng.guns.core.util;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 使用HttpURLConnection请求url的工具类
 */
public class HttpURLConnUtils {

    // 连接主机超时（30s）
    public static final int HTTP_CONNECT_TIMEOUT_30S = 30 * 1000;

    // 从主机读取数据超时（3min）
    public static final int HTTP_READ_TIMEOUT_3MIN = 180 * 1000;

    /**
     * GET method
     */
    public static String httpGET(String url) throws IOException {
        // 定义返回的结果
    	StringBuffer sb = new StringBuffer();

        // 声明要用的流对象
        BufferedReader reader = null;
        HttpURLConnection connection = null;

        try {
            String urlNameString = url;
            URL postUrl = new URL(urlNameString);
            connection = (HttpURLConnection) postUrl.openConnection();

            // 设置HttpURLConnection的一些公用配置
            setHttpURLConnCommPropreties(connection);

            // 私有配置
            connection.setRequestMethod("GET");
            connection.setRequestProperty("accept", "*/*");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            // 连接
            connection.connect();

            // 获取返回流
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));

            // 获取请求返回结果
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } finally {
            // 关闭流
            closeIO(null, reader);

            // 关闭连接
            if (null != connection) {
                connection.disconnect();
            }
        }

        return sb.toString();
    }

    /**
     * POST method
     */
    public static String httpPOST(String url, String jsonParam) throws IOException {
        // 定义返回结果
    	StringBuffer sb = new StringBuffer();

        // 声明要用的流对象
        BufferedReader reader = null;
        DataOutputStream out = null;
        HttpURLConnection connection = null;

        try {
            URL postUrl = new URL(url);
            connection = (HttpURLConnection) postUrl.openConnection();

            // 设置HttpURLConnection的一些公用配置
            setHttpURLConnCommPropreties(connection);

            // 私有配置
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            // 连接
            connection.connect();

            // 推送参数
            if (jsonParam != null) {
            	out = new DataOutputStream(connection.getOutputStream());
            	out.writeBytes(jsonParam);
            	out.flush();
            	out.close();
			}

            // 获取返回流
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));

            // 获取请求返回结果
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

        } finally {
            // 关闭流
            closeIO(out, reader);

            // 关闭连接
            if (null != connection) {
                connection.disconnect();
            }
        }

        // 返回结果
        return sb.toString();
    }

    /**
     * POST method with cookie
     */
    public static String httpPost_WithCookie(String url, String jsonParam, String cookie) throws IOException {
        // 定义返回结果
    	StringBuffer sb = new StringBuffer();

        // 声明要用的流对象
        BufferedReader reader = null;
        DataOutputStream out = null;
        HttpURLConnection connection = null;

        try {
            URL postUrl = new URL(url);
            connection = (HttpURLConnection) postUrl.openConnection();

            // 设置HttpURLConnection的一些公用配置
            setHttpURLConnCommPropreties(connection);

            // 私有配置
            connection.setRequestProperty("Cookie", cookie); // 设置login时返回的cookie
            connection.setRequestMethod("POST");

            // 连接
            connection.connect();

            // 推送参数
            out = new DataOutputStream(connection.getOutputStream());
            out.writeBytes(jsonParam);
            out.flush();
            out.close();

            // 获取返回流
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));

            // 获取请求返回结果
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } finally {
            // 关闭流
            closeIO(out, reader);

            // 关闭连接
            if (null != connection) {
                connection.disconnect();
            }
        }

        return sb.toString();
    }

    /**
     * POST method get cookie
     */
    public static Map<String, String> httpPost_GetCookie(String url, String jsonParam) throws IOException {
        // 定义一个map类型的结果集
        Map<String, String> map = new HashMap<String, String>();
        String cookie = "";
        StringBuffer sb = new StringBuffer();

        // 声明要用的流对象
        BufferedReader reader = null;
        DataOutputStream out = null;
        HttpURLConnection connection = null;

        try {
            URL postUrl = new URL(url);
            connection = (HttpURLConnection) postUrl.openConnection();

            // 设置HttpURLConnection的一些公用配置
            setHttpURLConnCommPropreties(connection);

            // 私有配置
            connection.setRequestMethod("POST"); // 设置访问类型
            connection.setRequestProperty("Connection", "Keep-Alive");

            // 连接
            connection.connect();

            // 推送参数
            out = new DataOutputStream(connection.getOutputStream());
            out.writeBytes(jsonParam);
            out.flush();
            out.close();

            // 获取返回流
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));// 设置返回数据编码
            cookie = connection.getHeaderField("Set-Cookie");// 取到所用的Cookie

            // 获取请求返回结果
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } finally {
            // 关闭流
            closeIO(out, reader);

            // 关闭连接
            if (null != connection) {
                connection.disconnect();
            }

            // 将返回结果及cookie保存到map中
            map.put("result", sb.toString());
            map.put("cookie", cookie);
        }

        return map;
    }

    /**
     * 设置HttpURLConnection的一些公用配置
     */
    private static void setHttpURLConnCommPropreties(HttpURLConnection connection) {
        // 设置连接主机超时（30s）
        connection.setConnectTimeout(HTTP_CONNECT_TIMEOUT_30S);

        // 设置从主机读取数据超时（3min）
        connection.setReadTimeout(HTTP_READ_TIMEOUT_3MIN);

        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);

        // 设置参数类型
        connection.setRequestProperty("Content-Type", "application/json");
    }

    /**
     * 关闭IO流
     */
    private static void closeIO(DataOutputStream out, BufferedReader reader) {
        // 关闭DataOutputStream
        try {
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 关闭BufferedReader
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}